package web.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

public class WebUtil {

	/**
	 * 获取应用根路径
	 * 
	 * @param request
	 * @return
	 */
	public static String getBasePath(HttpServletRequest request) {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/";

		return basePath;
	}
	
	/**
	 * 请求转发给客户端
	 * 
	 * @param request
	 * @param response
	 * @param uri
	 * @throws ServletException
	 * @throws IOException
	 */
	public static void renderHtml(HttpServletRequest request, HttpServletResponse response, String uri)
			throws ServletException, IOException {
		request.getRequestDispatcher(uri).forward(request, response);
	}

	/**
	 * 向客户端写JSON数据
	 * 
	 * @param response
	 * @param obj
	 */
	public static void renderJson(HttpServletResponse response, Object obj) {
		try {
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(JSON.toJSONString(obj));
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void renderJson(HttpServletResponse response, boolean success, String msg) {
		try {
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(JSON.toJSONString(new JsonResult(success, msg)));
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void  printException(Exception e, Writer writer) throws IOException{
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		
		e.printStackTrace(pw);
		pw.close();
		
		writer.write(sw.toString().replaceAll("\n", "<br>"));
	}
	
}
